import http from 'http'
import path from 'path'
import fs from 'fs'
import {createListener} from './download'

/**
 * @type {boolean} false 则使用本机中转
 */
const redirect = true
const port = 8888
const lzy = 'https://wws.lanzous.com'
const suffix = '.tar'
// https://wws.lanzous.com/iv3hRi9d27e

const app = http.createServer(async (req, res) => {
  // console.log(req.url)

  if (req.url === '/favicon.ico') {
    res.end()
  } else if (req.url === '/') {
    // main
    fs.createReadStream(path.resolve(__dirname, '../index.html')).pipe(res)
  } else if (/\/img\/.+/.test(req.url)) {
    // /img/:imgId
    const imgId = req.url.replace(/^\/img\//, '')
    const start = createListener({
      redirect,
      onStart: headers => {
        //     'content-type': 'application/octet-stream',
        //     'content-length': '269673',
        //     'content-disposition': 'attachment; filename= %E6%8A%95%E8%AF%89%E7%BB%93%E6%9E%9C.png.tar',
        if (headers['content-disposition']) headers['content-disposition'] = headers['content-disposition'].replace(new RegExp(`${suffix}$`), '')
        res.writeHead(200, headers)
      },
      onData: chunk => res.write(chunk),
      onEnd: (url) => {
        if (redirect) {
          res.writeHead(302, {
            'Location': url
          })
        }
        res.end()
      },
      onError: () => res.end('error occur'),
    })
    start({url: lzy + '/' + imgId})
  } else if (req.url === '/upload') {
    res.end('success')
    // console.log(req)
    // req.on("data", chunk => {
    //     console.log(chunk)
    // })
    const ws = fs.createWriteStream('/Users/chb/Desktop/tempDownload/upload.jpg')
    req.pipe(ws)
  }
})

app.listen(port)

console.log(`server run at ${port}`)
